<?php
/**
 * Created by PhpStorm.
 * Author: wenwenbin
 * Date: 2018/3/3
 * Time: 13:21
 */
namespace App\Http\Admin\Personnel\Models;

use App\Eloquent\Job\Resume\Resume;
use App\Eloquent\Oa\CompanyResume;
use App\Eloquent\Oa\CompanyUser;
use App\Eloquent\Oa\Contacts;
use App\Eloquent\Oa\EmployeeNumber;
use App\Eloquent\Oa\FlowInterview;
use App\Eloquent\Oa\PersonnelFile;
use App\Eloquent\Oa\WorkHistory;
use App\Eloquent\Oa\Workflow;
use App\Eloquent\UserRole;
use App\Repositories\OA\CompanyUserRepository;
use Framework\BaseClass\Http\Admin\Model;

class PassFlow extends Model
{
    public function getPassFlowList($companyId, $paging)
    {
        $temp = Workflow::where([['oa_company_id', $companyId], ['related_type', 23]])
            ->where(function ($query) {
                $query->where('dispose_code', 1100)->orWhere('dispose_code', 1200);
            })
            ->whereHas('interviewFlowInfo', function ($q) {
                $q->where('status', 0);
            })
            ->whereHas('interviewFlowInfo.resumeInfo')
            ->whereHas('interviewFlowInfo.recruitmentInfo');
        $count = $temp->count();
        $workFlowList = $temp->with('interviewFlowInfo.resumeInfo', 'interviewFlowInfo.recruitmentInfo.departmentInfo')
            ->offset(($paging['page'] - 1) * $paging['page_size'])
            ->take($paging['page_size'])
            ->get(['related_id']);
        foreach ($workFlowList as $workFlow) {
            $workFlow->id = $workFlow->interviewFlowInfo->id;
            $workFlow->name = $workFlow->interviewFlowInfo->resumeInfo->full_name;
            $workFlow->department = $workFlow->interviewFlowInfo->recruitmentInfo->departmentInfo ?
                $workFlow->interviewFlowInfo->recruitmentInfo->departmentInfo->name : '';
            $workFlow->position = $workFlow->interviewFlowInfo->recruitmentInfo->position;
            unset($workFlowList->interviewFlowInfo);
        }
        return ['list' => $workFlowList, 'totalRow' => $count];
    }

    public function joinCompany($id, $roleId, $employeeNumberId, $companyId, $prefix = null, $suffix = null, $count = 0)
    {
        \DB::beginTransaction();
        $result = true;
        foreach ($id as $k => $item) {
            if (is_null($employeeNumberId)) {
                if ($suffix + $k > 999999) xThrow(ERR_LOGIC, '工号后缀超过上限');
                $employeeNumber = $prefix . str_pad('', $count - mb_strlen($suffix), '0', STR_PAD_LEFT) . ($suffix + $k);
                $tempId = $this->createEmployeeNumber($employeeNumber, $companyId);
                $result = $this->createEmployeeInfo($item, $roleId, $tempId) && $result;
                if (!$result) break;
            } else {
                $result = $this->createEmployeeInfo($item, $roleId, $employeeNumberId) && $result;
                if (!$result) break;
            }
        }
        if ($result) {
            \DB::commit();
            return true;
        } else {
            \DB::rollBack();
            return false;
        }
    }

    public function createEmployeeNumber($employeeNumber, $companyId)
    {
        $employeeNumberInfo = EmployeeNumber::firstOrNew([
            'employee_number' => $employeeNumber,
            'oa_company_id'   => $companyId
        ]);
        if ($employeeNumberInfo->id) xThrow(ERR_OA_EMPLOYEE_NUMBER_ALREADY_EXIST);
        $employeeNumberInfo->save();
        return $employeeNumberInfo->id;
    }

    private function createEmployeeInfo($id, $roleId, $employeeNumber)
    {
        $interview = FlowInterview::has('resumeInfo')
            ->has('recruitmentInfo')
            ->with('resumeInfo.userInfo', 'recruitmentInfo')
            ->find($id);
        if (is_null($interview)) xThrow(ERR_OA_FLOW_INTERVIEW_NOT_EXIST);
        if (is_null($interview->resumeInfo->userInfo)) xThrow(ERR_CLIENT_USER_NOT_EXIST);

        //将入职状态改为已入职
        $interview->status = 1;
        $result = $interview->save();

        //添加到公司用户
        $companyUser = new CompanyUserRepository();
        $otherCompanyUserIsUse = $companyUser->find([['user_id', $interview->resumeInfo->user_id], ['is_use', 1]]);
        $companyUser->create([
            'oa_company_id'    => $interview->recruitmentInfo->belong_id,
            'oa_department_id' => $interview->recruitmentInfo->oa_department_id,
            'position'         => $interview->recruitmentInfo->position,
            'role_id'          => $roleId,
            'user_id'          => $interview->resumeInfo->user_id,
            'is_use'           => is_null($otherCompanyUserIsUse) ? 1 : 0,
            'type'             => 1
        ]);

        //绑定角色
        if (is_null($otherCompanyUserIsUse)) {
            $userRole = UserRole::firstOrNew(['user_id' => $interview->resumeInfo->user_id]);
            $userRole->role_id = $roleId;
            $result = $userRole->save() && $result;
        }


        //添加到通讯录
        $employee = new Contacts();
        $employee->fill([
            'user_id'           => $interview->resumeInfo->user_id,
            'mobile'            => $interview->resumeInfo->userInfo->customer_name,
            'oa_company_id'     => $interview->recruitmentInfo->belong_id,
            'oa_department_id'  => $interview->recruitmentInfo->oa_department_id,
            'name'              => $interview->resumeInfo->full_name,
            'position'          => $interview->recruitmentInfo->position,
            'email'             => '',
            'profile_photo_url' => '/images/global/default_avatar.png',
            'type'              => 1
        ]);
        $result = $employee->save() && $result;

        //将个人简历添加到入职简历
        $result = $this->addCompanyResume($interview->job_resume_id,
                $interview->recruitmentInfo->belong_id, $employee->id) && $result;

        //查找该联系人是否已占有工号，如果有，先让该工号的联系人清除，再将该联系人和选择的工号绑定
        $oldEmployeeNumber = EmployeeNumber::firstOrNew(['oa_contacts_id' => $employee->id]);
        if ($oldEmployeeNumber->id) {
            $oldEmployeeNumber->oa_contacts_id = 0;
            $result = $oldEmployeeNumber->save() && $result;
        }
        $newEmployeeNumber = EmployeeNumber::find($employeeNumber);
        if (is_null($newEmployeeNumber)) xThrow(ERR_OA_CONTACTS_NOT_EXIST);
        $newEmployeeNumber->oa_contacts_id = $employee->id;
        $result = $newEmployeeNumber->save() && $result;

        //生成人事档案
        $file = PersonnelFile::firstOrNew(
            [
                'oa_company_id'  => $interview->recruitmentInfo->belong_id,
                'oa_contacts_id' => $employee->id
            ]
        );
        $file->fill([
            'oa_department_id'              => $interview->recruitmentInfo->oa_department_id,
            'position'                      => $interview->recruitmentInfo->position,
            'name'                          => $interview->resumeInfo->full_name,
            'sex'                           => $interview->resumeInfo->gender,
            'ethnicity'                     => '',
            'birthplace'                    => '',
            'education'                     => $interview->resumeInfo->education,
            'birthdate'                     => $interview->resumeInfo->date_of_birth,
            'credential_type'               => $interview->resumeInfo->id_type,
            'credential_number'             => $interview->resumeInfo->id_number,
            'mobile'                        => $interview->resumeInfo->userInfo->customer_name,
            'email'                         => $employee->email,
            'address'                       => $interview->resumeInfo->address,
            'marital_status'                => $interview->resumeInfo->marital_status,
            'household_registratio_type'    => 0,
            'personnel_sources'             => '',
            'health_certificate_term'       => 0,
            'profile_photo_url'             => $employee->profile_photo_url,
            'note'                          => '',
            'accumulation_fund'             => 0,
            'accumulation_fund_base'        => 0,
            'accumulation_fund_adjust_time' => 0,
            'social_security_base'          => 0,
            'insured_adjust_time'           => 0,
            'status'                        => 1
        ]);
        $result = $file->save() && $result;

        //如果不存在工作记录，直接新建；如果已存在，并且岗位发生了调动，将原来的工作记录填上结束时间，并新建一条工作记录
        $oldWorkHistory = WorkHistory::where([['oa_contacts_id', $employee->id], ['end_time', 0]])->first();
        if (is_null($oldWorkHistory)) {
            $newWorkHistory = new WorkHistory;
            $newWorkHistory->fill([
                'oa_contacts_id'   => $employee->id,
                'oa_company_id'    => $employee->oa_company_id,
                'oa_department_id' => $employee->oa_department_id,
                'position'         => $employee->position,
                'start_time'       => time(),
                'belong_type'      => 1,
                'belong_id'        => $file->id
            ]);
            $result = $newWorkHistory->save() && $result;
        } elseif ($oldWorkHistory->oa_company_id != $employee->oa_company_id ||
            $oldWorkHistory->oa_department_id != $employee->oa_department_id ||
            $oldWorkHistory->position != $employee->position
        ) {
            $oldWorkHistory->end_time = time();
            $result = $oldWorkHistory->save() && $result;
            $newWorkHistory = new WorkHistory;
            $newWorkHistory->fill([
                'oa_contacts_id'   => $employee->id,
                'oa_company_id'    => $employee->oa_company_id,
                'oa_department_id' => $employee->oa_department_id,
                'position'         => $employee->position,
                'start_time'       => time(),
                'belong_type'      => 1,
                'belong_id'        => $file->id
            ]);
            $result = $newWorkHistory->save() && $result;
        }

        return $result;
    }

    /**
     * 添加人事档案（通过入职流程）
     * @author wenwenbin
     * @param $contactsId
     * @param $resumeId
     * @return bool
     */
    public function addPersonnelFile($contactsId, $resumeId)
    {
        $employee = Contacts::find($contactsId);
        if (is_null($employee)) xThrow(ERR_OA_CONTACTS_NOT_EXIST);
        $resume = Resume::find($resumeId);
        if (is_null($resume)) xThrow(ERR_JOB_RESUME_NOT_EXIST);
        $companyUser = CompanyUser::where([['oa_company_id', $employee->oa_company_id],
            ['user_id', $employee->user_id]])->first();
        if (is_null($companyUser)) xThrow(ERR_OA_COMPANY_USER_NOT_EXIST);
        \DB::beginTransaction();

        //将公司员工的入职状态改为已入职
        $companyUser->type = 1;
        $result = $companyUser->save();

        //更新角色
        $userRole = UserRole::where('user_id', $companyUser->user_id)->first();
        $userRole->role_id = $companyUser->role_id;
        $result = $userRole->save() && $result;

        //将个人简历添加到入职简历
        $result = $this->addCompanyResume($resumeId, $employee->oa_company_id, $employee->id) && $result;

        //生成人事档案
        $file = PersonnelFile::firstOrNew(
            [
                'oa_company_id'  => $employee->oa_company_id,
                'oa_contacts_id' => $employee->id
            ]
        );
        $file->fill([
            'oa_department_id'              => $employee->oa_department_id,
            'position'                      => $employee->position,
            'name'                          => $resume->full_name,
            'sex'                           => $resume->gender,
            'ethnicity'                     => '',
            'birthplace'                    => '',
            'education'                     => $resume->education,
            'birthdate'                     => $resume->date_of_birth,
            'credential_type'               => $resume->id_type,
            'credential_number'             => $resume->id_number,
            'mobile'                        => $employee->mobile,
            'email'                         => $employee->email,
            'address'                       => $resume->address,
            'marital_status'                => $resume->marital_status,
            'household_registratio_type'    => 0,
            'personnel_sources'             => '',
            'health_certificate_term'       => 0,
            'profile_photo_url'             => $employee->profile_photo_url,
            'note'                          => '',
            'accumulation_fund'             => 0,
            'accumulation_fund_base'        => 0,
            'accumulation_fund_adjust_time' => 0,
            'social_security_base'          => 0,
            'insured_adjust_time'           => 0,
            'status'                        => 1
        ]);
        $result = $file->save() && $result;

        //如果不存在工作记录，直接新建；如果已存在，并且岗位发生了调动，将原来的工作记录填上结束时间，并新建一条工作记录
        $oldWorkHistory = WorkHistory::where([['oa_contacts_id', $employee->id], ['end_time', 0]])->first();
        if (is_null($oldWorkHistory)) {
            $newWorkHistory = new WorkHistory;
            $newWorkHistory->fill([
                'oa_contacts_id'   => $employee->id,
                'oa_company_id'    => $employee->oa_company_id,
                'oa_department_id' => $employee->oa_department_id,
                'position'         => $employee->position,
                'start_time'       => time(),
                'belong_type'      => 1,
                'belong_id'        => $file->id
            ]);
            $result = $newWorkHistory->save() && $result;
        } elseif ($oldWorkHistory->oa_company_id != $employee->oa_company_id ||
            $oldWorkHistory->oa_department_id != $employee->oa_department_id ||
            $oldWorkHistory->position != $employee->position
        ) {
            $oldWorkHistory->end_time = time();
            $result = $oldWorkHistory->save() && $result;
            $newWorkHistory = new WorkHistory;
            $newWorkHistory->fill([
                'oa_contacts_id'   => $employee->id,
                'oa_company_id'    => $employee->oa_company_id,
                'oa_department_id' => $employee->oa_department_id,
                'position'         => $employee->position,
                'start_time'       => time(),
                'belong_type'      => 1,
                'belong_id'        => $file->id
            ]);
            $result = $newWorkHistory->save() && $result;
        }

        if ($result) {
            \DB::commit();
            return true;
        } else {
            \DB::rollBack();
            return false;
        }
    }

    public function addCompanyResume($resumeId, $companyId, $contactsId)
    {
        $resume = Resume::find($resumeId);
        if (is_null($resume)) xThrow(ERR_JOB_RESUME_NOT_EXIST);
        $collection = CompanyResume::firstOrNew(['oa_company_id' => $companyId, 'oa_contacts_id' => $contactsId]);
        $collection->fill($resume->toArray());
        return $collection->save();
    }
}